﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
using System.Windows.Forms;
using System.Xml;


namespace MediaWPF
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            if (!File.Exists("currentplaylist.xml"))
            {
                XDocument xmlDoc;
                // creation du fichier currentPlaylist.xml
                xmlDoc = new XDocument();
                xmlDoc.Add(new XElement("Fichiers"));
                xmlDoc.Save("currentPlaylist.xml");
            }
        }

        #region Open Media
        private void bouton_open_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                mediaElement1.Source = new Uri(ofd.FileName);
                mediaElement1.Play();
                bouton_play.Content = "Pause";
            }
        }
        #endregion

        private void add_file_Click(object sender, RoutedEventArgs e)
        {
            XDocument xmlDoc;

            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.ShowDialog();
            if (!File.Exists("currentplaylist.xml"))
            {
                // creation du fichier currentPlaylist.xml
                xmlDoc = new XDocument();
                xmlDoc.Add(new XElement("Fichiers"));
                xmlDoc.Save("currentPlaylist.xml");
            }

            // récupération de l'id3tag
            string[] files = new string[] { "", ""};

            files[0] = openFileDialog1.FileName;

            List<getFileTags.tagStruct> tags = getFileTags.getFileTagsFromPaths(files);
            getFileTags.tagStruct mytag = tags[0];

            // ajout du fichier dans le xml
            xmlDoc = XDocument.Load("currentPlaylist.xml");
            xmlDoc.Element("Fichiers")
                .Add(new XElement("Fichier", 
                    new XElement("Type", "Musique"),
                    new XElement("Path", openFileDialog1.FileName), 
                    new XElement("Artiste", mytag._artists),
                    new XElement("Titre", mytag._title)));
            xmlDoc.Save("currentPlaylist.xml");
            read_xml_and_fill_list();
        }

        private void add_dir_playlist_Click(object sender, RoutedEventArgs e)
        {
            XDocument xmlDoc;
            string[] files;
            int filecount;
            FolderBrowserDialog dirbrowser = new FolderBrowserDialog();

            if (!File.Exists("currentplaylist.xml"))
            {
                // creation du fichier currentPlaylist.xml
                xmlDoc = new XDocument();
                xmlDoc.Add(new XElement("Fichiers"));
                xmlDoc.Save("currentPlaylist.xml");
            }
            // ajout du contenu du repertoire dans le fichier xml
            xmlDoc = XDocument.Load("currentPlaylist.xml");
            dirbrowser.ShowDialog();
            files = Directory.GetFileSystemEntries(dirbrowser.SelectedPath);
            filecount = files.GetUpperBound(0) + 1;

            List<getFileTags.tagStruct> tags = getFileTags.getFileTagsFromPaths(files);
            getFileTags.tagStruct mytag;

            for (int i = 0; i < filecount; i++)
            {
                mytag = tags[i];
                xmlDoc.Element("Fichiers")
                    .Add(new XElement("Fichier",
                    new XElement("Type", "Musique"),
                    new XElement("Path", files[i]),
                    new XElement("Artiste", mytag._artists),
                    new XElement("Titre", mytag._title)));
                xmlDoc.Save("currentPlaylist.xml");
            }
        }

        private void listBox2_DoubleClick(object sender, EventArgs e)
        {
            mediaElement1.Source = new Uri(listBox1.SelectedItem.ToString());
        }

        private void add_file_media_Click(object sender, RoutedEventArgs e)
        {
            XDocument xmlDoc;

            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.ShowDialog();
            if (!File.Exists("currentmedia.xml"))
            {
                // creation du fichier currentmedia.xml
                xmlDoc = new XDocument();
                xmlDoc.Add(new XElement("Fichiers"));
                xmlDoc.Save("currentmedia.xml");
            }

            // get file type
            string fileType = "Inconnu";
            string[] pathSplitted = new string[] {"", "", "", "", "", "", ""};
            pathSplitted = openFileDialog1.FileName.Split('.');
            if (pathSplitted[1] == "mp3" || pathSplitted[1] == "ogg" || pathSplitted[1] == "mpc")
            {
                fileType = "Musique";
            }
            else if (pathSplitted[1] == "avi" || pathSplitted[1] == "mpeg" || pathSplitted[1] == "mp4")
            {
                fileType = "Video";
            }
            else if (pathSplitted[1] == "jpg" || pathSplitted[1] == "jpeg" || pathSplitted[1] == "bmp" || pathSplitted[1] == "png")
            {
                fileType = "Image";
            }

            // ajout du fichier dans le xml
            xmlDoc = XDocument.Load("currentmedia.xml");
            if (fileType == "Musique" || fileType == "Video")
            {
                // get id3tag
                string[] files = new string[] { "", "" };
                files[0] = openFileDialog1.FileName;
                List<getFileTags.tagStruct> tags = getFileTags.getFileTagsFromPaths(files);
                getFileTags.tagStruct mytag;
                mytag = tags[0];

                xmlDoc.Element("Fichiers")
                        .Add(new XElement("Fichier",
                        new XElement("Type", fileType),
                        new XElement("Path", openFileDialog1.FileName),
                        new XElement("Artiste", mytag._artists),
                        new XElement("Titre", mytag._title)));
                
            }
            else
            {
                xmlDoc.Element("Fichiers")
                        .Add(new XElement("Fichier",
                        new XElement("Type", fileType),
                        new XElement("Path", openFileDialog1.FileName)));
            }
            xmlDoc.Save("currentmedia.xml");
        }

        private void add_dir_media_Click(object sender, RoutedEventArgs e)
        {
            XDocument xmlDoc;
            string[] files;
            int filecount;
            FolderBrowserDialog dirbrowser = new FolderBrowserDialog();

            if (!File.Exists("currentmedia.xml"))
            {
                // creation du fichier currentmedia.xml
                xmlDoc = new XDocument();
                xmlDoc.Add(new XElement("Fichiers"));
                xmlDoc.Save("currentmedia.xml");
            }
            // ajout du contenu du repertoire dans le fichier xml
            xmlDoc = XDocument.Load("currentmedia.xml");
            dirbrowser.ShowDialog();
            files = Directory.GetFileSystemEntries(dirbrowser.SelectedPath);
            filecount = files.GetUpperBound(0) + 1;

            List<getFileTags.tagStruct> tags = getFileTags.getFileTagsFromPaths(files);
            getFileTags.tagStruct mytag;

            for (int i = 0; i < filecount; i++)
            {
                // get file type
                string fileType = "Inconnu";
                string[] pathSplitted = new string[] { "", "", "", "", "", "", "" };
                pathSplitted = files[i].Split('.');
                if (pathSplitted[1] == "mp3" || pathSplitted[1] == "ogg" || pathSplitted[1] == "mpc")
                {
                    fileType = "Musique";
                }
                else if (pathSplitted[1] == "avi" || pathSplitted[1] == "mpeg" || pathSplitted[1] == "mp4")
                {
                    fileType = "Video";
                }
                else if (pathSplitted[1] == "jpg" || pathSplitted[1] == "jpeg" || pathSplitted[1] == "bmp" || pathSplitted[1] == "png")
                {
                    fileType = "Image";
                }
                mytag = tags[i];
                xmlDoc.Element("Fichiers")
                    .Add(new XElement("Fichier",
                    new XElement("Type", fileType),
                    new XElement("Path", files[i]),
                    new XElement("Artiste", mytag._artists),
                    new XElement("Titre", mytag._title)));
                  xmlDoc.Save("currentmedia.xml");
            }
        }

       

        private void read_xml_and_fill_list()
        {
            int i = 0;
            listBox1.Items.Clear();
            
            XPathDocument docxml = new XPathDocument("currentPlaylist.xml");
            XPathNavigator lir = docxml.CreateNavigator();
            XPathNodeIterator iterateur = lir.Select("Fichiers/Fichier");
            while (iterateur.MoveNext())
            {
                string artiste = iterateur.Current.SelectSingleNode("Artiste").Value;
                string titre = iterateur.Current.SelectSingleNode("Titre").Value;
                if (artiste == "")
                {
                    artiste = "Unknown";
                }
                if (titre == "")
                {
                    titre = "Unknown";
                }
                    listBox1.Items.Insert(i, (artiste + " - " + titre));
              
                i++;
            }
        }

        private void bouton_delete_Click(object sender, RoutedEventArgs e)
        {
            if (listBox1.Items.IsEmpty == false && listBox1.SelectedValue != null)
            {
                string test = listBox1.SelectedValue.ToString();
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("currentPlaylist.xml");
                XmlElement elmRoot = xmlDoc.DocumentElement;
                XmlNodeList lstFichier = xmlDoc.GetElementsByTagName("Fichier");
                foreach (XmlNode node in lstFichier)
                {
                    int flag = 0;
                    XmlNodeList lstChildren = node.ChildNodes;

                    foreach (XmlNode dir in lstChildren)
                    {
                        if (dir.InnerText == test)
                        {
                            node.ParentNode.RemoveChild(node);
                            xmlDoc.Save("currentPlaylist.xml");
                            flag = 1;
                            break;

                        }
                    }
                    if (flag == 1)
                    {
                        read_xml_and_fill_list();
                        break;
                    }
                }
            }
        }

        private void bouton_stop_Click(object sender, RoutedEventArgs e)
        {
            mediaElement1.Pause();
            bouton_play.Content = "Play";
        }

        private void bouton_play_Click(object sender, RoutedEventArgs e)
        {
            if (bouton_play.Content.ToString() == "Play")
            {
                bouton_play.Content = "Pause";
                mediaElement1.Play();
            }
            else
            {
                bouton_play.Content = "Play";
                mediaElement1.Pause();
            }
        }

        private void save_playlist_Click(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists("Playlist") == false)
            {
                Directory.CreateDirectory("Playlist");
            }
            if (File.Exists("Playlist/" + textbox_playlist_name.Text.ToString() + ".xml"))
            {
                File.Delete("Playlist/" + textbox_playlist_name.Text.ToString() + ".xml");
            }
            if (textbox_playlist_name.Text != "")
            {
                File.Copy("currentPlaylist.xml", "Playlist/" + textbox_playlist_name.Text.ToString() + ".xml");
            }
        }

        

    }
}
